<template>
  <el-dialog :visible.sync="visible" :close-on-click-modal="false" :title="$tt('title_pick_down')"
    custom-class="dialog_extra">


    <el-form v-loading="loading" ref="detailListForm" :model="data" :rules="rules">
      <el-form-item :label="$tt('label_pick_code')">
        <div class="bold">{{ data.pickNo }}</div>
      </el-form-item>
      <el-form-item :label="$tt('label_wave_plan')">
        <div class="bold">{{ data.waveNo ? data.waveNo : $tt('data_none') }}</div>
      </el-form-item>
      <el-form-item prop="taskDetailList"></el-form-item>
      <ex_super_table :data="data.taskDetailList" v-bind="option" height="400">

      </ex_super_table>


    </el-form>
    <span slot="footer" class="dialog_footer">
      <el-button @click="visible = false"> {{ $tt('label_cancel') }}</el-button>
      <el-button type="primary" @click="submit">{{ $tt('label_confirm')
      }}</el-button>
    </span>

  </el-dialog>
</template>

<script>

import container_selec_input from '@/component/wms/container_selec_input.vue';

import popover_sn_detail from '@/component/wms/popover_sn_detail'


let defaultPickItem = {
  pickingTaskDate: null,

  pickingPerson: null,
  pickingPersonId: null,
  pickingPersonName: null,
  pickingPersonCode: null,
  pickCount: null,
  areaId: null,
  areaCode: null,
  locationId: null,
  locationCode: null,
  // containerCode: null,
  // subContainerCode: null,
  cartContainerNo: "",
}
export default {
  route_manual: true,
  components: { container_selec_input, popover_sn_detail, },

  data() {
    return {
      visible: false,
      loading: false,
      data: {},
      option: {
        model: [
          {
            key: 'boxNo', label: 'label_box_code', 'min-width': 150, if: () => !this.SkuOutbound,
            propertyFilter: true, sortable: true,
          },
          { key: 'skuBarcode', label: 'label_sku_code', propertyFilter: true, sortable: true, },
          { key: 'skuNameCn', label: 'label_sku_name', formater: (r, c, v) => this.$formatNameCode(v, r.skuNameEn) },
          {
            key: 'locationCode', 'min-width': 250,
            label: { _key: 'label_xxx_type_arrow', i18n: true, type: 'label_recommend_location', code: '', count: 'label_plan_pick_count' },
            propertyFilter: true, sortable: true,
            render: (h, { row }) => {
              const item = row
              return (<div>【{item.locationCode}】→(<span class="bold color_info">{item.pickCount}</span>)</div>)
            }
          },
          // {
          //   key: 'recommendInfo', label: 'label_recommend_warehouse_area_location_info', 'min-width': 300,
          //   render: (h, { row }) => {
          //     const list = row.recommendObjs ? row.recommendObjs : []
          //     return h('div', {},
          //       list.map(it => {
          //         return (<div>【{it.location}】→(<span class="bold color_success">{it.count}</span>)</div>)
          //       })
          //     )
          //   }
          // },
          { key: 'stockUseType', label: 'label_stock_usage', 'width': 120, sortable: true, formatter: (r, c, v) => this.$enumShow(v, "StockUsageEnum") },

          { key: 'pickCount', label: 'label_plan_pick_count', width: 120, sortable: true, },
          {
            key: 'actualPickingCount', label: 'label_actual_pick_count', width: 120, sortable: true,
            render: (h, scope) => {

              return h(popover_sn_detail, {
                props: {
                  value: scope.row.actualPickingCount,
                  list: scope.row.actualPickingDetail,
                  option: {
                    stockUsage: "stockUseType",
                    snCode: "stockSkuSnCode",
                  },
                },
              })
            },
          },


          {
            key: 'pickDetail', 'min-width': 550,
            label: { _key: 'label_xxx_type_arrow', i18n: true, type: 'label_actual_pick_location', code: 'label_pick_car_code', count: 'label_actual_pick_count' },
            "label-class-name": "label_require_before",
            // renderHeader: (h, { column, $index }) => (<span class="table-require">{column.label}</span>),
            render: (h, { row, index }) => {
              const item = row
              let form_item = null
              if (!this.disabledRow(row)) {
                let pickCountList = (<el-form-item
                  class="flex_cell"
                  prop={`taskDetailList.${index}.pickDetail`}
                  rules={this.rules['pickCount']}
                >
                  {
                    item.pickDetail ? item.pickDetail.map((itemPick, i) => {
                      if (itemPick.isSn) {
                        return (
                          <ex_super_input value={itemPick.skuSnCode} key={`pickSnDiv${item.id}_${i}`}
                            class="w_fill" onInput={
                              e => { this.$set(itemPick, "skuSnCode", e.trim()) }
                            } />
                        )
                      } else {
                        return (
                          <el-input-number value={itemPick.pickCount} key={`pickCountDiv${item.id}_${i}`}
                            placeholder={this.$tt('label_actual_pick_count')}
                            min={0} max={this.pickCountMaxRow(item, itemPick)} step-strictly
                            onInput={e => this.$set(itemPick, "pickCount", e)}
                            class="w_fill"></el-input-number>
                        )
                      }
                    }) : null
                  }
                </el-form-item>)
                // if (!item.isSn) {
                // } else {
                //   pickCountList = (<el-form-item
                //     class="flex_cell"
                //     prop={`taskDetailList.${index}.pickDetail`}
                //     rules={this.rules['skuSnCode']}
                //   >
                //     {
                //       item.pickDetail ? item.pickDetail.map((itemPick, i) => (
                //         <ex_super_input value={itemPick.skuSnCode} key={`pickSnDiv${item.id}_${i}`}
                //           class="w_fill" onInput={
                //             e => {
                //               this.$set(itemPick, "skuSnCode", e)
                //             }
                //           } />
                //       )) : null
                //     }
                //   </el-form-item>)
                // }
                form_item = (
                  <div class="flex_row">

                    <el-form-item
                      class="flex_cell"
                      prop={`taskDetailList.${index}.pickDetail`}
                      rules={this.rules['locationId']}
                    >
                      {
                        item.pickDetail ? item.pickDetail.map((itemPick, i) => (
                          <base_location_select value={itemPick.locationId} checkArea={false} key={`locationId${item.id}_${i}`}
                            placeholder="label_actual_pick_location"
                            class="w_fill" onChangeItem={
                              e => {
                                if (!e) e = { id: null, code: null }
                                this.$set(itemPick, "locationId", e.id)
                                itemPick.locationCode = e.code
                              }
                            } />
                        )) : null
                      }
                    </el-form-item>

                    <el-form-item
                      class="flex_cell"
                      prop={`taskDetailList.${index}.pickDetail`}
                      rules={!this.TOB ? this.rules['cartContainerNo'] : null}
                    >
                      {
                        item.pickDetail ? item.pickDetail.map((itemPick, i) => (
                          h(container_selec_input, {
                            class: "w_fill",
                            key: `cartContainerNo${itemPick.id}_${i}`,
                            props: {
                              placeholder: "label_pick_car_code",
                              value: itemPick.cartContainerId,
                              clearable: !!item.boxNo,
                            },
                            on: {
                              input: (e) => this.$set(itemPick, "cartContainerId", e),
                              'changeItem': (e) => this.$set(itemPick, "cartContainerNo", e.code),
                            },
                          })
                        )) : null
                      }
                    </el-form-item>

                    {!item.boxNo ? pickCountList : null}
                    <el-form-item
                      class="flex_cell"
                      prop={`taskDetailList.${index}.pickDetail`}
                    >
                      {
                        item.pickDetail ? item.pickDetail.map((itemPick, i) => (
                          <common_user_select value={itemPick.pickingPersonId} key={`pickingPersonId${item.id}_${i}`}
                            currentLabel={itemPick.pickingPerson}
                            class="w_fill" onChangeItem={
                              e => {
                                if (!e) e = { userName: null, userCode: null }
                                itemPick.pickingPerson = e.userName
                                itemPick.pickingPersonName = e.userName
                                itemPick.pickingPersonCode = e.userCode
                              }
                            } />
                        )) : null
                      }
                    </el-form-item>
                    <el-form-item
                      class="flex_cell"
                      prop={`taskDetailList.${index}.pickDetail`}
                    >
                      {
                        item.pickDetail ? item.pickDetail.map((itemPick, i) => (
                          <ex_super_input value={itemPick.pickingTaskDate} key={`pickingTaskDate${item.id}_${i}`}
                            type="date-picker" attrs={{ type: 'datetime' }}
                            class="w_fill" onInput={
                              e => {
                                this.$set(itemPick, "pickingTaskDate", e)
                              }
                            } />
                        )) : null
                      }
                    </el-form-item>
                  </div>
                )
              }
              return (<div>
                {item.actualPickingDetail.map((it, index) => (
                  <div>【{it.locationCode}】→【{it.cartContainerNo}】(<span class="bold color_success">{it.count}</span>)</div>
                ))}
                {form_item}
              </div >)
            }
          },


          {
            type: 'operate', width: 160, operate: [
              {
                label: 'label_insert', if: (row) => !row.boxNo,
                disabled: row => {
                  if (this.disabledRow(row)) return true
                  if (row.boxNo) return row.pickDetail.length >= 1
                  return row.pickDetail.length >= this.surplusRow(row)
                },
                click: row => this.insertRow(row)
              },
              {
                label: 'label_sn_code', if: (row) => !row.boxNo,
                disabled: row => {
                  if (this.disabledRow(row)) return true
                  if (row.boxNo) return row.pickDetail.length >= 1
                  return row.pickDetail.length >= this.surplusRow(row)
                },
                click: row => this.insertRowSn(row)
              },
              {
                label: 'label_remove', class: 'button_text_danger',
                disabled: row => this.disabledRow(row) || row.pickDetail.length <= 0,
                click: row => this.removeRow(row)
              },
            ]
          }
        ]
      },
      rules: {
        pickCount: {
          required: true, type: 'array',
          validator: (r, v, cb) => {
            if (v.some(it => ((!(Number(it.pickCount) > 0)) && !it.skuSnCode))) {
              return cb(this.$tt('tip_can_no_empty'))
            }
            cb()
          },
          trigger: 'change'
        },
        // skuSnCode: {
        //   type: 'array', required: true,
        //   defaultField: {
        //     type: "object", required: true,
        //     fields: {
        //       skuSnCode: { message: this.$tt('tip_can_no_empty'), required: true }
        //     },
        //   },
        // },
        // pickCount: {
        //   type: 'array', required: true,
        //   defaultField: {
        //     type: "object", required: true,
        //     fields: {
        //       pickCount: { message: this.$tt('tip_can_no_empty'), type: "number", min: 1, required: true }
        //     },
        //   },
        // },
        locationId: {
          type: 'array', required: true,
          defaultField: {
            type: "object", required: true,
            fields: {
              locationId: { message: this.$tt('tip_can_no_empty'), type: "string", required: true }
            },
          },
        },
        cartContainerNo: {
          type: 'array', required: true,
          defaultField: {
            type: "object", required: true,
            fields: {
              cartContainerNo: { message: this.$tt('tip_can_no_empty'), type: "string", required: true }
            },
          },
        },

      },
    }
  },
  props: {


  },

  computed: {
    TOB() {
      return this.data.bizType == 'TOB'
    },
    SkuOutbound() {
      return this.data.taskDetailList ? this.data.taskDetailList.every(it => !it.boxNo) : true
    },

  },
  methods: {
    rowClassMethod({ row, rowIndex }) {
      if (this.surplusRow(row) == 0) {
        return "back_success_light back_success_light_hover"
      }
      return ""
    },
    insertRow(row) {
      row.pickDetail.push(this.createDefaultPickItem(row))
    },
    insertRowSn(row) {
      const item = this.createDefaultPickItem(row)
      item.isSn = true
      row.pickDetail.push(item)
    },
    removeRow(row) {
      row.pickDetail.splice(row.pickDetail.length - 1, 1)
    },
    selectablePickDetail(item, row) {
      return item.pickCount > 0 || !!row.boxNo || !!item.skuSnCode
    },
    surplusRow(row) {
      return row.pickCount - row.actualPickingCount
    },
    pickCountMaxRow(row, item) {
      return this.surplusRow(row) - _.reduce(row.pickDetail, (sum, it) => it == item ? sum : (sum + it.pickCount), 0)
    },
    disabledRow(row) {
      return this.surplusRow(row) <= 0
    },
    createDefaultPickItem(row) {
      let item = _.cloneDeep(defaultPickItem);
      item.edit = true
      item.pickingTaskDate = new Date().getTime()
      let user = this.$loginUser
      if (user) {
        item.pickingPersonId = user.userId
        item.pickingPerson = user.userName
        item.pickingPersonCode = user.userCode
      }
      if (row) {
        item.PickingTaskId = row.pickTaskId
        item.skuId = row.skuId
        item.skuOnlyCode = row.skuOnlyCode
        item.skuBarcode = row.skuBarcode
      }
      return item
    },
    show({ data }) {
      this.visible = true
      this.loading = true
      this.data = {}
      this.$ajax({
        url: "/wms-api/outbound/OutboundPickingTaskRpc/detail.json",
        method: 'post',
        data,
        success: (res) => {
          res.data.taskDetailList.forEach(it => {
            if (it.actualPickingDetail) {
              it.actualPickingDetail = JSON.parse(it.actualPickingDetail)
            } else {
              it.actualPickingDetail = []
            }
            it.pickDetail = []
            if (!this.disabledRow(it)) {
              this.insertRow(it)
            }
          }
          )
          this.data = res.data
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    hide() {
      this.visible = false
    },

    submit() {

      this.$refs['detailListForm'].validate((valid) => {
        if (valid) {
          let list = []
          let isAnomaly = false
          this.data.taskDetailList.forEach(it => {
            it.pickDetail.filter(item => this.selectablePickDetail(item, it)).forEach(item => {
              // item.locationId
              item.stockUseType = "COMMON_SALE"
              if (it.locationCode != item.locationCode) {
                isAnomaly = true
              }
              if (!!it.boxNo) {
                item.pickCount = this.surplusRow(it)
                item.boxNo = it.boxNo
                item.subContainerCode = it.subContainerCode
              } else if (!!item.skuSnCode) {
                item.pickCount = 1
                item.stockUseType = "REFUND_SALE"
              }
              
              list.push(item)
            })
          })
          if (isAnomaly) {
            this.$prompt(this.$tt('tip_pick_location_recommond_diff_input_reason'), this.$tt('label_tip'), {
              type: 'warning',
              inputValidator: (value) => {
                if (_.isEmpty(value.trim())) {
                  return this.$tt("tip_can_no_empty")
                }
                return true
              },

            }).then(({ value }) => {
              list.forEach(it => {
                it.anomalyRemark = value
              })
              this.submitNet(list)
            }).catch(() => {

            });
          } else {
            this.submitNet(list)

          }


        } else {
          this.$message.error(this.$tt('form_validate_error'))
          return false;
        }
      });


    },
    submitNet(list) {
      this.$ajax({
        url: "/wms-api/outbound/OutboundPickingTaskRecordDetailRpc/addBatch.json",
        method: 'post', type: 'json',
        loading: true,
        data: {
          pickingRecordList: list
        },
        success: (res) => {

          this.$emitPage('outbound>picking_task_record', 'reload')
          this.$message.success(this.$tt('tip_submit_success'))
          this.visible = false
          this.$emit('submitSuccess')

        },
        complete: () => {
        }
      })
    },
  }
}
</script>
